package com.antilia.infomaresme;

import org.apache.wicket.protocol.http.WebSession;
import org.apache.wicket.request.Request;

import com.antilia.infomaresme.data.dataobjects.Language;
import com.antilia.infomaresme.data.dataobjects.User;


/**
 * @author Ernesto Reinaldo Barreiro (reiern70@gmail.com)
 *
 */
public class InfomaresmeSession extends WebSession implements IAuthenticableSession  {

	private static final long serialVersionUID = 1L;
	

	private Language language;
	
	private String userId;
	
	private User user;
	
	
	@Override
	public boolean authenticate(String username, String password) {
		if(userId != null)
			return true;
		User user = InfomaresmeApplication.getQAApplication().getAuthenticator().authenticate(username, password);
		if(user != null) {
			userId = username;
			setLanguage(user.getLanguage());
			return true;
		}
		return false;
	}
	
	/**
	 * @param request
	 */
	public InfomaresmeSession(Request request) {
		super(request);
	}

	
	/**
	 * Returns the session.
	 * @return
	 */
	public static InfomaresmeSession getSession() {
		return (InfomaresmeSession)get();
	}


	public Language getLanguage() {
		return language;
	}


	public void setLanguage(Language language) {
		setLocale(language.getLocale());
		this.language = language;
	}


	public boolean isAuthenticated() {
		return (userId != null);
	}


	public boolean signOut() {
		// TODO Auto-generated method stub
		userId = null;
		return true;
	}


	public String getUserId() {
		return userId;
	}


	public void setUserId(String userId) {
		this.userId = userId;
		user = null;
	}

	public User getUser() {
		if(user == null) {
			user = InfomaresmeApplication.getQAApplication().getUsersDao().loadById(userId);
		}
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

}